# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2022/3/7 10:09 下午
# @Author : 曹庭
# @File : passport.py
# @Software: PyCharm

from . import api
from course import db, models, redis_store, constants
from flask import g, current_app, request, jsonify, session, make_response
from course.utils.response_code import RET
from course.utils.commons import login_required
import re
from course.models import User
from sqlalchemy.exc import IntegrityError
from flask_wtf.csrf import generate_csrf


# @api.after_request
# def after_request(response):
#     # 通过generate_csrf()生成csrf_token的值
#     csrf_token = generate_csrf()
#     # 设置到cookie中
#     response.set_cookie("csrf_token", csrf_token)
#     return response

@api.route("/register", methods=["POST"])
def register():
    """
    注册
    请求参数：用户名、邮箱、密码
    :return: json
    """
    request_dict = request.get_json()
    user_name = request_dict.get("user_name")
    mail = request_dict.get("mail")
    password = request_dict.get("password")

    # 校验参数
    if not all([user_name, mail, password]):
        return jsonify(code=RET.PARAMERR, errmag="参数不完整")

    # 判断邮箱格式
    if not re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", mail):
        return jsonify(code=RET.PARAMERR, errmag="邮箱格式不正确")

    # 保存用户的注册信息到数据库中
    user = User(user_name=user_name, mail=mail)
    user.password = password
    try:
        db.session.add(user)
        db.session.commit()
    except IntegrityError as e:
        db.session.rollback()
        # 表示用户名和邮箱有重复值
        current_app.logger.error(e)
        return jsonify(code=RET.DATAEXIST, msg="用户名或邮箱已存在")
    except Exception as e:
        db.session.rollback()
        # 表示用户名和邮箱有重复值
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="查询数据库异常")

    # 保存登录状态到session中
    session["user_id"] = user.id
    session["user_name"] = user_name
    session["avatar"] = ""
    session["mail"] = mail
    session["vip"] = user.is_vip
    # 返回结果
    return jsonify(code=RET.OK, msg="注册成功")


@api.route("/login", methods=["POST"])
def login():
    """
    用户登录
    参数：用户名：用户名、邮箱  密码：密码
    :return:
    """
    # 获取参数
    req_dict = request.get_json()
    user_name = req_dict.get("username")
    password = req_dict.get("password")
    # print(user_name)
    # print(password)

    # 校验参数
    if not all([user_name, password]):
        return jsonify(code=RET.PARAMERR, errmag="参数不完整")

    # 判断用户名是否为邮箱
    if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", user_name):
        try:
            user = User.query.filter_by(mail=user_name).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR, msg="邮箱不存在")
        else:
            if user is not None:
                # 表示邮箱存在,需校验密码
                result = user.check_password(password)
                if result:
                    # 为True则表示验证成功
                    # 保存登录状态到session中
                    session["user_id"] = user.id
                    session["user_name"] = user.user_name
                    session["mail"] = user_name
                    session["is_vip"] = user.is_vip
                    print("+++++++++++++++++++++")
                    print(user.avatar_url)
                    print(user.avatar_url is not None)
                    print("+++++++++++++++++++++")
                    if user.avatar_url is not None:
                        session["avatar"] = constants.QINIU_URL_DOMAIN + user.avatar_url
                    else:
                        session["avatar"] = ""
                    # 返回结果
                    return jsonify(code=RET.OK, msg="登录成功", data={"user_id": user.id})
                else:
                    return jsonify(code=RET.PWDERR, msg="密码输入错误")
            else:

                return jsonify(code=RET.PWDERR, msg="用户名未被注册")

    try:
        user = User.query.filter_by(user_name=user_name).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库查询失败")
    else:
        if user is not None:
            # 表示用户名存在,需校验密码
            result = user.check_password(password)
            if result:
                # 为True则表示验证成功
                # 保存登录状态到session中
                session["user_id"] = user.id
                session["user_name"] = user_name
                session["mail"] = user.mail
                session["is_vip"] = user.is_vip
                print("+++++++++++++++++++++")
                print(user.avatar_url)
                print("+++++++++++++++++++++")
                if user.avatar_url is not None:
                    session["avatar"] = constants.QINIU_URL_DOMAIN + user.avatar_url
                else:
                    session["avatar"] = ""
                print(user.id)
                print(user_name)
                print(user.mail)
                print(user.is_vip)
                # 返回结果
                return jsonify(code=RET.OK, msg="登录成功", data={"user_id": user.id})
            else:
                return jsonify(code=RET.PWDERR, msg="密码输入错误")
        else:
            return jsonify(code=RET.PWDERR, msg="该用户名未被注册")


@api.route("/check_login", methods=["POST"])
def check_login():
    """
    检查登录状态
    :return:
    """
    # 尝试从session中获取用户的名字
    user_name = session.get("user_name")
    user_id = session.get("user_id")
    avatar = session.get("avatar")
    is_vip = session.get("is_vip")
    # 如果session中数据name名字存在，则表示用户已登录，否则未登录
    if user_name is not None:
        return jsonify(code=RET.OK, msg="true",
                       data={"user_name": user_name, "user_id": user_id, "avatar": avatar, "is_vip": is_vip})
    else:
        return jsonify(code=RET.SESSIONERR, msg="flase")


@api.route("/logout", methods=["POST"])
def logout():
    """
    退出
    :return:
    """
    # 清除session信息
    session.clear()
    return jsonify(code=RET.OK, msg="OK")


@api.route("/user_list", methods=["POST"])
@login_required
def get_user_list():
    """
    获取所有用户信息
    :return:
    """
    user_id = g.user_id

    if user_id != 1:
        return jsonify(code=RET.RIGHTSERR, msg="此账号无权限")

    req_dict = request.get_json()
    curr = req_dict.get("curr")
    nums = req_dict.get("nums")
    searchParams = req_dict.get("searchParams")
    print(searchParams)

    user_id = searchParams["user_id"]
    user_name = searchParams["user_name"]
    mail = searchParams["mail"]

    print(user_id)
    print(user_name)
    print(mail)
    if user_id == "" and user_name == "" and mail == "":
        try:
            paginate = User.query.paginate(page=curr, per_page=nums)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR, msg="数据库查询失败")

        user_list = []

        users = paginate.items
        total = paginate.total
        for user in users:
            user_dict = user.to_dict()
            print(user_dict)
            user_list.append(user_dict)
        print(user_list)

        # 返回结果
        return jsonify(code=RET.OK, count=total, msg="", data=user_list)

    try:
        if user_id:
            paginate = User.query.filter_by(id=user_id).paginate(page=curr, per_page=nums)
        else:
            paginate = User.query.filter(User.user_name.like('%{}%'.format(user_name)),
                                         User.mail.like('%{}%'.format(mail))).paginate(page=curr,
                                                                                       per_page=nums)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库查询失败")

    user_list = []
    users = paginate.items
    total = paginate.total
    for user in users:
        user_dict = user.to_dict()
        print(user_dict)
        user_list.append(user_dict)
    print(user_list)

    # 返回结果
    return jsonify(code=RET.OK, count=total, msg="", data=user_list)


@api.route("/editPassword", methods=["POST"])
@login_required
def edit_password():
    """
    修改密码
    :return:
    """
    # 尝试从session中获取用户的名字
    user_id = g.user_id
    print(user_id)

    request_dict = request.get_json()
    print(request_dict)
    onepassword = request_dict.get("onepassword")
    twopassword = request_dict.get("twopassword")

    # 校验参数
    if not all([onepassword, twopassword]):
        return jsonify(code=RET.PARAMERR, errmag="参数不完整")

    # 密码校验
    if onepassword != twopassword:
        return jsonify(code=RET.PWDERR, errmag="密码不一致，请重新设置")

    # 保存文件名到数据库中
    try:
        user = User.query.filter_by(id=user_id).first()
        user.password = onepassword
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR, errmsg="数据保存失败")

    return jsonify(code=RET.OK, errmsg="保存成功")
